import bleUtils from '../../utils/bluetooth'
import api from '../../../api/index'
const bleManager = require('../../utils/BLE/CRBleManager.js')
let timeValue = null
let interval = null
Page({
	/**
   * 页面的初始数据
   */
	data: {
		bindDeviceId: null,
		devicelist: [],
		actions: [],
		bindDevice: [],
		saveDevice: {},
		showDialog: false,
		bindDeviceTextInfo: '',
		loading: false,
		bleAvaible: true,
    beforeClose: null,
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.doInitBlue()
		// this.setBleCallBack()
		this.get()
  },
  // 蓝牙初始化
  doInitBlue() {
    bleUtils.initBlueTooth().then((res) => {
			this.setData({
				bleAvaible: true
			})
      this.doGetBluetoothAdapterState()
    }).catch(error => {
			this.setData({
				bleAvaible: false
			})
		})
  },
	setBleCallBack (){
    const that = this
    //蓝牙管理
    bleManager.setDelegate({
        //搜索结束
        SearchComplete: that.searchComplete,
    })
  },
  // 获取蓝牙适配器状态
  doGetBluetoothAdapterState() {
    bleUtils.getBluetoothAdapterState()
  },
  //开始搜索蓝牙设备
  doStartSearchBlueTooth() {
		console.log('搜搜2222')
    bleUtils.startSearchBlueTooth().then((res) => {
      this.doOnBluetoothDeviceFound()
    })
		// bleManager.startSearch()
  },
	searchComplete(devicesList){
		console.log(devicesList,'devicesListdevicesList')
    const filterValue = devicesList.filter(item => item.name.indexOf('PC-60F') > -1)
		if(filterValue.length > 0) {
			const actions =  [
				{ name: filterValue[0].name, subname: filterValue[0].deviceID, deviceID: filterValue[0].deviceID },
			]
			this.setData({
				actions: actions
			})
		} else {
		}
  },
  // 监听搜素到新的蓝牙设备
  doOnBluetoothDeviceFound() {
    bleUtils.onBluetoothDeviceFound().then((res) => {
      console.log(res, '监听搜素到新的蓝牙设备成功')
			const filterValue = res.filter(item => item.name.indexOf('PC-60F') > -1)
			if(filterValue.length > 0) {
				const actions =  [
					{ name: filterValue[0].name, subname: filterValue[0].deviceID, deviceID: filterValue[0].deviceID },
				]
				this.setData({
					actions: actions
				})
				// 搜索到可用的蓝牙设备，停止搜索
				bleUtils.stopSearchBlueTooth()
			} else {
				//没有搜索到可用设备，重新搜索
				console.log('没有搜索到可用设备，重新搜索')
				// this.doStartSearchBlueTooth()
				// setTimeout(() => {
				// 	this.setData({
				// 		showDialog: false
				// 	})
				// }, 1500);
			}
    })
  },
	// 链接设备
	goBindEq() {
		// if(!this.data.bleAvaible) {
		// 	wx.showToast({
		// 		title: '蓝牙初始化失败,请打开蓝牙',
		// 		icon: 'none',
		// 		duration: 2000
		// 	})
		// 	return
		// }
		this.setData({
			showDialog: true
		})
		this.onConfirm()
	},
  // 封装异步关闭函数
  dialogClost() {
    this.setData({
      beforeClose: (action) =>
        new Promise((resolve) => {
          if (action === 'confirm') {
            // 确定按钮
            resolve(false)
          } else if (action === 'cancel') {
            // 取消按钮
            resolve(true)
          }
        }),
    })
  },
	createDiaTitle() {
		let num = 15
		let value = ''
		this.timeValue = setInterval(() => {
			value = `蓝牙搜索中(${num}s)...`
			if (num === 0) {
				clearInterval(this.timeValue)
				value = `蓝牙搜索完成`
			} else {
				num --
			}
			this.setData({
				bindDeviceTextInfo: value
			})
		}, 1000)
	},
  onConfirm() {
    this.dialogClost()
		clearInterval(this.timeValue)
    // bleManager.stopSearch()
    // this.setData({
		// 	bindDeviceTextInfo: '蓝牙搜索中...'
		// })
    // // this.doStartSearchBlueTooth()
		// bleManager.startSearch()
		this.createDiaTitle()
		let pages=getCurrentPages();  //获取当前页面
    let beforePage=pages[pages.length-2]  //获取上一个页面的实例
    if(beforePage.doSearch) {
      beforePage.doSearch(2)
    }
		this.interval = setInterval(() => {
			console.log(beforePage.getSearchDevice(), '哈哈哈哈')
			const data = beforePage.getSearchDevice()
			this.setData({
				actions: data
			})
		}, 2000)
  },
	onCancel() {
		console.log('取消了')
		this.dialogClost()
		clearInterval(this.timeValue)
		clearInterval(this.interval)
		this.setData({
			bindDeviceTextInfo: ''
		})
		// 停止搜索
		wx.stopBluetoothDevicesDiscovery()
	},
	onClose() {
    this.setData({ showDialog: false });
  },
	onSelectA(e) {
		console.log(e,'AAAA')
		clearInterval(this.interval)
    const value = e.currentTarget.dataset.item
		this.setData({
			saveDevice: value
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name:this.data.saveDevice.name,deviceID: this.data.saveDevice.deviceID}
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.putData(saveDataList, '保存')
      this.goBackDoTest(this.data.saveDevice)
		}
  },
  handlerDetail(e) {
    const value = e.currentTarget.dataset.item
    this.goBackDoTest(value)
  },
  goBackDoTest(device) {
    let pages=getCurrentPages();  //获取当前页面
    let beforePage=pages[pages.length-2]  //获取上一个页面的实例
    if(beforePage.connectDevice) {
      beforePage.connectDevice(device)
    }
    wx.navigateBack({
      delta: 1
    })
  },
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'bloodoxygen')
				if(listValue.length > 0) {
					this.setData({
						bindDevice: listValue[0].devicelist
					})
				}
		  }
			this.setData({
				loading: false
			})
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	delEq(e) {
		const name = e.currentTarget.dataset.name
		const data = this.data.bindDevice.filter(item => {
			return item.name !== name
		})
		this.putData(data, '删除')
	},
	putData(deviceIdList, type) {
		let num = [{name:'bloodoxygen',devicelist: deviceIdList}]
		num = JSON.stringify(num)
		this.doSavedevice(num, type)
	},
	// 储存设备
	async doSavedevice(result, type) {
		try {
		  await api.post('/api/user/storage/set', {
				data: {
					'key': 'devicelist',
					'value': result
				}
				})
				wx.showToast({
					title: `${type}成功`,
					icon: 'none',
					duration: 3000
				})
				this.setData({ showDialog: false });
				this.get()
			} catch (e) {
				console.log('put->', e)
			}
	  },

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {
		clearInterval(this.interval)
	},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		clearInterval(this.interval)
	},
	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
